#!/usr/bin/env python

from ..protocols.d2rs import D2RSPacket, MOTDResponse, GameListResponse

def D2RSUnpacker(packet):
	if packet.messageID is GameListResponse:
		packet.requestID, packet.index, packet.playerCount, packet.status = struct.unpack("<Hibi", packet.messageData[0:11])
		
		if config.scrapeGameList:
			if status > 0:
				list = []
				
				start = 0
				
				while True:
					title, description = sock.server.data[start+14:start+messageLength].split("\x00")[:-1]
					
					if title:
						list.append([title, description, playerCount])
					
					timestamp = str(datetime.today().replace(microsecond = 0))
					
					query = """
					INSERT INTO `bnet_games`
					SET
						`game_title` = '%(title)s',
						`game_description` = '%(description)s',
						`game_players` = %(players)i,
						`game_created` = '%(timestamp)s',
						`game_updated` = '%(timestamp)s',
						`type_id` = %(typeID)i, `realm_id` = %(realmID)i,
						`game_expansion` = %(gameExpansion)i,
						`game_ladder` = %(gameLadder)i,
						`game_hardcore` = %(gameHardcore)i,
						`game_difficulty` = %(gameDifficulty)i 
					ON DUPLICATE KEY UPDATE
						`game_description` = '%(description)s',
						`game_players` = %(players)i,
						`game_updated` = '%(timestamp)s'
					""" % {
						"title": title,
						"description": description,
						"players": playerCount,
						"timestamp": timestamp,
						"typeID": typeID,
						"realmID": realmID,
						"gameExpansion": gameExpansion,
						"gameLadder": gameLadder,
						"gameHardcore": gameHardcore,
						"gameDifficulty": gameDifficulty
					}
					
					print query
					db.query(query)
					
					print "Title:" + title
					print "Description: " + description
					print "Players: " + str(playerCount)
					print
	
	if packet.messageID is MOTDResponse:
		if config.scrapeGameList:
			startLogging = packet.socket

D2RSPacket.addEventListener("unpack", D2RSUnpacker)